package com.dongan.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dongan.mapper.ModuleDetailsMapper;
import com.dongan.mapper.ModuleMapper;
import com.dongan.pojo.Codes;
import com.dongan.mapper.CodesMapper;
import com.dongan.pojo.File;
import com.dongan.pojo.Module;
import com.dongan.pojo.ModuleDetails;
import com.dongan.service.CodesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dongan.service.FileService;
import com.dongan.service.ModuleDetailsService;
import com.dongan.service.ModuleService;
import com.dongan.utils.ResultResponseUtil;
import com.dongan.utils.SerialNumber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 模块 服务实现类
 * </p>
 *
 * @author longTao
 * @since 2021-06-15
 */
@Service
public class ModuleServiceImpl extends ServiceImpl<ModuleMapper, Module> implements ModuleService {

    @Autowired
    private ModuleMapper mapper;
    @Autowired
    private ModuleDetailsService moduleDetailsMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private CodesService codesService;

    @Override
    @Transactional
    public void insertModule(Module module, List<ModuleDetails> moduleDetails) {
        int insert = mapper.insert(module);
        if (insert>0){
            BigDecimal priceSum = new BigDecimal(0);
            for (int i = 0; i < moduleDetails.size(); i++) {
                ModuleDetails m = moduleDetails.get(i);
                int n=i+1;
                //物料序号
                m.setDetailsNumber(Long.valueOf(n));
                //小计
                m.setSubtotal(m.getCostPrice().multiply(BigDecimal.valueOf(m.getAmount())));
                //可用数量
                m.setResidualAmount(m.getAmount());


                //
                System.out.println("module.getId() = " + module.getId());
                m.setParentId(module.getId());
                //总计
                priceSum = priceSum.add(m.getSubtotal());

            }
            module.setCostPriceSum(priceSum);
            boolean b = moduleDetailsMapper.saveBatch(moduleDetails);
            if (b) {
                //修改商品物料设计表
                File file = new File();
                //file.setProductId(module.getProductId());
                UpdateWrapper<File> fileUpdateWrapper=new UpdateWrapper<>();
                fileUpdateWrapper.eq("PRODUCT_ID",module.getProductId());
                file.setDesignModuleTag("W001-1");
                fileService.update(file,fileUpdateWrapper);
                SerialNumber.moduleSN=SerialNumber.moduleSN+1;
                Codes codes=new Codes();codes.setId(2L);codes.setDefValue(Integer.valueOf(SerialNumber.moduleSN).toString());
               codesService.updateById(codes);
            }
        }
    }
}
